<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Exceptions\JWTException;

class JWTMiddleware
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        try {
            // 检查是否有 Authorization header
            $token = JWTAuth::getToken();
            if (!$token) {
                return response()->json([
                    'code' => 401,
                    'message' => '缺少认证令牌，请在 Authorization header 中提供 Bearer token',
                    'data' => null
                ], 401);
            }

            // 先解析令牌获取荷载
            $payload = JWTAuth::parseToken()->getPayload();
            $userId = $payload->get('sub'); // 获取用户ID
            
            // 通过ID查找用户
            $user = User::find($userId);

            if (!$user) {
                return response()->json([
                    'code' => 401,
                    'message' => '令牌无效或用户不存在',
                    'data' => null
                ], 401);
            }
            
            // 设置当前认证用户
            Auth::setUser($user);
            $request->merge(['user_id' => $user->id]);

        } catch (TokenExpiredException $e) {
            return response()->json([
                'code' => 401,
                'message' => '令牌已过期，请重新登录',
                'data' => null
            ], 401);
        } catch (TokenInvalidException $e) {
            return response()->json([
                'code' => 401,
                'message' => '令牌无效，请重新登录',
                'data' => null
            ], 401);
        } catch (JWTException $e) {
            return response()->json([
                'code' => 401,
                'message' => '令牌解析失败，请检查 Authorization header 格式',
                'data' => null
            ], 401);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 500,
                'message' => '服务器内部错误：' . $e->getMessage(),
                'data' => null
            ], 500);
        }

        return $next($request);
    }
}